const {
  img
} = require('../../images/img.js')
Page({
  data: {
    /** 最小缩放百分比 */
    minScale: 30,
    /** 最大缩放百分比 */
    maxScale: 100,
    /** 单次缩放百分比增量 */
    increaseScale: 5,
    /** 缩放比例 */
    scale: 1,
    touchType: '',
    start: {
      x: 0,
      y: 0
    },
    touches: [],
    change: {
      x: 0,
      y: 0
    },
    /** 是否正在绘制 */
    drawing: false,
    // 视图宽度
    viewWidth: 0,
    // 视图高度
    viewHeight: 0,
    // 画布绘制的图像宽度
    width: 376,
    // 画布绘制的图像高度
    height: 400

  },


  drawImg() {
    // 拦截频繁绘制
    if (this.data.drawing) return;
    const that = this;
    this.data.drawing = true;
    var ctx = this.canvasContext;
    // 改变坐标系原点
    const clearRe = ctx.clearRect(0, 0, 4000, 4000) // 清空画布
    ctx.translate(this.data.change.x, this.data.change.y);
    // https://img.mianfeiwendang.com/pic/45d799de5037cf19899c4f8f/1-991-png_6_0_0_0_0_0_0_1973.25_2791.125-1629-0-2710-1629.jpg
    // const clearRe = ctx.clearRect(0, 0, 4000, 4000) // 清空画布
    // const bg = this.canvas.createImage();
    // bg.onload = () => {
    //   // textCtx.drawImage(bg, 0, 0, canvas.width, canvas.height)
    //   // ctx.clearRect(0, 0, that.data.width, that.data.height) // 清空画布
    //   ctx.drawImage(bg, 0, 0, that.data.width * that.data.scale, that.data.height * that.data.scale);
    //   that.data.drawing = false
    // }
    // bg.src = img
    // ctx.clearRect(0, 0, that.data.width, that.data.height) // 清空画布
    ctx.drawImage(this.bg, 0, 0, that.data.width * that.data.scale, that.data.height * that.data.scale);
    that.data.drawing = false
    // console.log(clearRe);



    // 绘制图片
    // ctx.drawImage(img, 0, 0, this.data.width * this.data.scale, this.data.height * this.data.scale);
    // ctx.draw(false, () => {
    //   this.data.drawing = false
    // });
  },
  /**
   * 限制 x、y 拖动范围，禁止滑出边界
   * @param {number} x
   * @param {number} y
   */
  checkRange(point) {
    point.x = Math.min(Math.max(point.x, -this.data.width * this.data.scale + this.data.viewWidth), 0);
    point.y = Math.min(Math.max(point.y, -this.data.height * this.data.scale + this.data.viewHeight), 0);
    return point;
  },
  /**
   * 缩放画布
   * @param {boolean} reduce 是否缩小，否则为放大
   */
  scaleCanvas(reduce, e) {
    let last = this.data.scale;
    let scale = Math.round(last * 100); // 转为整数计算，无精度丢失问题
    if (reduce) { // 缩小 / 鼠标滚轮向下滚动
      scale = scale > this.data.minScale ? scale - this.data.increaseScale : this.data.minScale;
    } else { // 放大 / 鼠标滚轮向上滚动
      scale = scale < this.data.maxScale ? scale + this.data.increaseScale : this.data.maxScale;
    }
    if (last !== scale / 100) {
      this.data.scale = scale / 100;
      this.data.start = {
        x: 0,
        y: 0
      };
      // 参考问题：有一个长4000px、宽4000px的四方形ABCD，A点的坐标固定在(-2000,-2000)，
      // 			该四边形上有一个点E，坐标为(-100,-300)，将该四方形复制一份并缩小到90%后，
      // 			新四边形的A点坐标为多少时可使新四边形的E点与原四边形的E点重合？
      // 预期效果：从图中选取某点（参照物）为中心点进行缩放，缩放时无论图像怎么变化，该点位置始终固定不变
      // 计算方法：以相同起点先计算缩放前后两点间的距离，再加上原图像偏移量即可
      this.movingCanvas({
        isScaled: true,
        pageX: (e.pageX - this.data.change.x) * (1 - this.data.scale / last),
        pageY: (e.pageY - this.data.change.y) * (1 - this.data.scale / last),
      });
    }
  },

  onTouchStart(e) {
    this.data.start.x = e.touches[0].pageX;
    this.data.start.y = e.touches[0].pageY;
    this.data.touchType = '';
  },
  /**
   * 计算两点间距
   * @param {Object} touches 
   */
  getDistanceByTouches(touches) {
    // 根据勾股定理求两点间距离
    const a = touches[1].pageX - touches[0].pageX;
    const b = touches[1].pageY - touches[0].pageY;
    const c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
    // 求两点间的中点坐标
    // 1. a、b可能为负值
    // 2. 在求a、b时，如用touches[1]减touches[0]，则求中点坐标也得用touches[1]减a/2、b/2
    // 3. 同理，在求a、b时，也可用touches[0]减touches[1]，则求中点坐标也得用touches[0]减a/2、b/2
    const x = touches[1].pageX - a / 2;
    const y = touches[1].pageY - b / 2;
    // return { a: Math.abs(a), b: Math.abs(b), c, x, y };
    return {
      c,
      x,
      y
    };
  },

  touchmoveHandler(e) {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      this.onTouchMove(e)
    }, 17);
      // this.onTouchMove(e)

  },
  onTouchMove(e) {
    if (e.touches.length === 2) { // 双点触摸 / 缩放
      if (this.data.touchType === 'scale') {
        const start = this.getDistanceByTouches(this.data.touches);
        const end = this.getDistanceByTouches(e.touches);

        if (Math.abs(start.c - end.c) >= 10) { // 滑动多长距离触发缩放
          this.data.touches = e.touches;
          this.scaleCanvas(
            start.c > end.c, // 两点间距变小=缩小
            {
              pageX: end.x,
              pageY: end.y
            }
          );
        }
      } else {
        this.data.touches = e.touches;
      }
      this.data.touchType = 'scale';
    } else {
      if (this.data.touchType === 'scale') {
        // 从双点触摸变成单点触摸 / 从缩放变成拖动
        this.data.start.x = e.touches[0].pageX;
        this.data.start.y = e.touches[0].pageY;
        this.data.touchType = 'move';
        return;
      }
      this.movingCanvas(e.touches[0])
      this.data.touchType = 'move';
    }
  },
  throttle(fn, interval) {
    var enterTime = 0; //触发的时间
    var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
    return function () {
      var context = this;
      var backTime = new Date(); //第一次函数return即触发的时间
      if (backTime - enterTime > gapTime) {
        fn.apply(context, arguments);
        enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
      }
    };
  },

  onTouchMove1(e) {
    const fn = this.throttle(this.onTouchMove, 16);
    return fn(e);
  },

  movingCanvas(touche) {
    let point = {
      x: this.data.change.x + touche.pageX - this.data.start.x,
      y: this.data.change.y + touche.pageY - this.data.start.y
    };
    // this.checkRange(point);
    if (touche.isScaled || this.data.change.x !== point.x || this.data.change.y !== point.y) {
      this.data.change = point;
      this.drawImg();
      this.data.start.x = touche.pageX;
      this.data.start.y = touche.pageY;
    }
  },

  // 按钮放大缩小图片
  imgUp() {
    var that = this
    //console.log("up")    
    var scroll_h = this.data.scrollHeight
    var scroll_w = this.data.scrollWidth
    let touch = this.data.touch
    let newScale = touch.scale + 0.2
    let c_w = 0.5 * (scroll_w - touch.baseWidth) // 新的x轴偏移量
    let c_h = 0.5 * (scroll_h - touch.baseHeight) // 新的y轴偏移量

    //console.log(newScale)
    if (newScale >= 2) {
      newScale = 2
    }
    if (newScale <= 0.2) {
      newScale = 0.2
    }
    let offsetX = (touch.offsetX - c_w) * newScale / touch.scale + c_w
    let offsetY = (touch.offsetY - c_h) * newScale / touch.scale + c_h
    // 赋值 新的 => 旧的
    that.setData({
      'touch.scale': newScale,
      'touch.offsetX': offsetX,
      'touch.offsetY': offsetY
    })
  },
  //点击缩小
  imgDn() {
    var that = this
    var scroll_h = this.data.scrollHeight
    var scroll_w = this.data.scrollWidth
    let touch = this.data.touch
    let newScale = touch.scale - 0.2
    let c_w = 0.5 * (scroll_w - touch.baseWidth)
    let c_h = 0.5 * (scroll_h - touch.baseHeight)
    if (newScale >= 2) {
      newScale = 2
    }
    if (newScale <= 0.2) {
      newScale = 0.2
    }
    let offsetX = (touch.offsetX - c_w) * newScale / touch.scale + c_w
    let offsetY = (touch.offsetY - c_h) * newScale / touch.scale + c_h
    // 赋值 新的 => 旧的 
    that.setData({
      'touch.scale': newScale,
      'touch.offsetX': offsetX,
      'touch.offsetY': offsetY
    })
  },

  onReady() {
    const that = this;
    const sys = wx.getSystemInfoSync();
    this.data.viewWidth = sys.screenWidth;
    this.data.viewHeight = sys.screenHeight;
    // this.canvasContext = wx.createCanvasContext('gameCanvas');

    // this.drawImg()
    wx.createSelectorQuery().select('#myCanvas').fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node // 重点1
        that.canvas = canvas;
        const canvasContext = canvas.getContext('2d') // 重点2

        console.log('canvasContext', canvasContext);
        const ctx = canvasContext;
        const dpr = wx.getSystemInfoSync().pixelRatio
        // that.canvas = canvasContext.canvas
        that.canvasContext = canvasContext

        // this.drawImg()
        // canvas.canvas.width = res[0].width
        // canvas.canvas.height = res[0].height
        const bg = canvas.createImage();
        bg.onload = (res) => {
          // textCtx.drawImage(bg, 0, 0, canvas.width, canvas.height)
          // this.img = bg;
          // console.log(bg);
          //  this.drawImg()
          this.bg = bg;

          ctx.drawImage(bg, 0, 0, that.data.width * that.data.scale, that.data.height * that.data.scale);
          this.data.drawing = false
          // this.drawImg()
        }
        // bg.src = 'https://img.mianfeiwendang.com/pic/45d799de5037cf19899c4f8f/1-991-png_6_0_0_0_0_0_0_1973.25_2791.125-1629-0-2710-1629.jpg'
        bg.src = img;
      })
    // 监听 PC 端鼠标滚轮
    const platformLists = ['windows', 'mac'];
    if (platformLists.includes(sys.platform)) {
      window.addEventListener('mousewheel', (e) => {
        this.data.scaleCanvas(e.deltaY > 0, e);
      });
    }
  },
})